package exam.security;

import cn.hutool.json.JSONUtil;
import exam.utils.Msg;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 解决认证过的用户访问需要权限才能访问的资源时的异常
 */
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);

        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        Msg msg = Msg.fail().setMessage("权限不足");

        outputStream.write(JSONUtil.toJsonStr(msg).getBytes("UTF-8"));

        outputStream.flush();
        outputStream.close();
    }
}
